package com.harboursoftware.xstorage.integration

import com.harboursoftware.xstorage.TestDatabaseProvider 
import com.harboursoftware.xstorage.db.sql.UserSqlDao 
import com.harboursoftware.xstorage.model.XUser 

import org.apache.commons.io.IOUtils;
import org.jets3t.service.Jets3tProperties 
import org.jets3t.service.impl.rest.httpclient.RestS3Service 
import org.jets3t.service.model.S3Bucket  
import org.jets3t.service.model.S3Object 
import org.jets3t.service.security.AWSCredentials 
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test 

class ObjectOperationsTest {
    def awsAccessKey = '0PN5J17HBGZHT7JJ3X82'
    def awsSecretAccessKey = 'uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o'
    def email = 'testuser@harboursoftware.com'
    def bucketName = 'harboursoftware'
    def s3Service
    
    @Before
    void setUp() {
        Jets3tProperties props = new Jets3tProperties();
        props.setProperty("s3service.https-only", 'false')
        props.setProperty('s3service.internal-error-retry-max', '0')
        AWSCredentials credentials = new AWSCredentials(awsAccessKey, awsSecretAccessKey);
        s3Service = new RestS3Service(credentials, 'x-storage-test', null, props);
        
        //准备user数据
        def databaseProvider = new TestDatabaseProvider()
        databaseProvider.recreateDatabase()
        def userDao = new UserSqlDao(databaseProvider)
        def user = new XUser(null, awsAccessKey, awsSecretAccessKey, email, email)
        userDao.saveUser user
        
        //创建bucket
        s3Service.createBucket bucketName
    }
    
    @After
    void tearDown() {
        s3Service.deleteBucket bucketName
        s3Service = null
    }
    @Test
    void test_put_get_delete_object() {
        def bucket = new S3Bucket(bucketName)
        def key = "testobject"
        def dataString = "adsfdasfdasfdsafdasdfadsfasdfsdafdsafdsafasfasddas";
        def object = new S3Object(bucket, key, dataString)
        
        s3Service.putObject(bucket, object)
        def presistedObject = s3Service.getObject(bucket, key)
        def presistedDataString = IOUtils.toString(presistedObject.dataInputStream)
        
        assert presistedDataString == dataString
        
        s3Service.deleteObject(bucket, key)
        
        try{
            s3Service.getObject(bucket, key)
        } catch (e) {
            return
        }
        Assert.fail()
    }
    
    void test_post_object() {
        
    }
    
    void test_get_object_acl() {
        
    }
}
